package com.wx.house.manager.api.capital.controller;

import java.awt.image.BufferedImage;
import java.io.*;
import java.math.BigDecimal;
import java.util.Arrays;
import java.util.Base64;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.wx.house.common.util.IDUtils;
import com.wx.house.common.util.JsonUtils;
import net.coobird.thumbnailator.Thumbnails;
import net.sf.json.util.JSONUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.core.io.ResourceLoader;
import org.springframework.util.Base64Utils;
import org.springframework.util.ObjectUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.github.pagehelper.PageInfo;
import com.github.pagehelper.util.StringUtil;
import com.wx.house.common.assembly.alyidcard.IDCardUtil;
import com.wx.house.common.assembly.alyidcard.IDocrResult;
import com.wx.house.common.base.BaseController;
import com.wx.house.common.base.ProjectConfiguration;
import com.wx.house.common.exception.BusinessException;
import com.wx.house.common.util.JwtUtils;
import com.wx.house.common.util.MapUtil;
import com.wx.house.core.pojo.base.Result;
import com.wx.house.core.pojo.po.SysAdminDetail;
import com.wx.house.core.pojo.po.fileupload.AttaUpload;
import com.wx.house.core.pojo.vo.SysAdminDetailVo;
import com.wx.house.core.pojo.vo.TenantUserVo;
import com.wx.house.manager.api.capital.service.SysAdminDetailService;
import com.wx.house.manager.api.capital.service.impl.SysAdminDetailServiceImpl;
import com.wx.house.manager.api.capital.text.IDinformation;
import com.wx.house.manager.api.capital.text.SysAdminDetailPame;
import com.wx.house.manager.api.fileupload.service.FileUploadService;
import com.wx.house.manager.api.permission.service.SysAdminService;

import io.jsonwebtoken.Claims;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.multipart.MultipartFile;

/**
 * @date ：Created in 2019/11/26 下午 03:40 @description：
 * @version: ：V
 */
@RestController
@RequestMapping("SysAdminDetail/")
@Slf4j
@RequiredArgsConstructor
@Api(tags = "实名认证")
@Validated
public class SysAdminDetailController extends BaseController {
	private static final String CODE = "ALY:ID_CODE:%s";
    @Resource
    private SysAdminDetailService sysAdminDetailService;
    @Resource
    private IDCardUtil iDCardUtil;
    @Resource
    private FileUploadService fileUploadService;
    @Resource
    private final ResourceLoader resourceLoader;
    @Resource
    private ProjectConfiguration projectConfiguration;

    @PostMapping("addReal/")
    @ApiOperation(value = "提交实名认证", notes = "提交实名认证")
    public Result addReal(@RequestBody @Validated SysAdminDetailPame sysAdminDetailPame, HttpServletRequest request) {
        try {
            String token = request.getHeader("authorization");
//			if(!ObjectUtils.isEmpty(sysAdminDetailService.selectIdCardNumber(sysAdminDetailPame.getIdCardNumber()))) {
//				return Result.error("当前身份证号已实名认证");
//			}
            String name=redisUtil().get(String.format(CODE,sysAdminDetailPame.getIdCardNumber()));
            if(StringUtil.isEmpty(name)) {
            	return Result.error("提交的身份证图片已过期");
            }
            if(!name.equals(sysAdminDetailPame.getReallyName())) {
            	return Result.error("提交的身份证与提交的身份证不符");
            }
            iDCardUtil.validated(sysAdminDetailPame.getIdCardNumber(), sysAdminDetailPame.getReallyName());
            // step1. 解析token
            Claims claims = JwtUtils.builder().token(token).build().claims();
            // step2. 从token获取参数,获取账号类型
            String adminId = claims.get("id").toString();
            if (ObjectUtils.isEmpty(sysAdminDetailService.updateCard(adminId, sysAdminDetailPame))) {
                return Result.error("提交实名认证失败");
            }
            return Result.success();
        } catch (Exception e) {
            throw new BusinessException("身份证信息不匹配");
        }
    }

    @PostMapping("idCardAutoOCR/")
    @ApiOperation(value = "提交实名认证2", notes = "提交实名认证")
    public Result addReal(HttpServletRequest request, @RequestParam("multipartFile") MultipartFile multipartFile,
    		@RequestParam("OcrName") String OcrName,@RequestParam("OcrCode") String OcrCode,@RequestParam("id") String id) throws IOException {
    	AttaUpload upload =null;
        Integer desMaxWidth=856;
        Integer desMaxHeight=540;
        if(StringUtil.isEmpty(id)) {
        	id=String.valueOf(IDUtils.genItemId(12));
        }
        String filename = multipartFile.getOriginalFilename();//获取上传文件的文件名
        InputStream file = null;
        file = multipartFile.getInputStream();
        BufferedImage bim = ImageIO.read(file);
        int srcWidth = bim.getWidth();
        int srcHeight = bim.getHeight();
        Thumbnails.Builder builder = Thumbnails.of(bim).outputFormat("jpeg");
        // 指定大小（宽或高超出会才会被缩放）
        if (srcWidth > desMaxWidth || srcHeight > desMaxHeight) {
            builder.size(desMaxWidth, desMaxHeight);
        } else {
            //宽高均小，指定原大小
            builder.size(srcWidth, srcHeight);
        }
        // 写入到内存
        ByteArrayOutputStream baos = new ByteArrayOutputStream(); //字节输出流（写入到内存）
        builder.toOutputStream(baos);
        IDocrResult iDocrResult = iDCardUtil.OcrValidated(baos.toByteArray());
        if("1".equals(iDocrResult.getCode())) {
        	IDinformation iDinformation=MapUtil.mapToPojo((HashMap<String, String>)iDocrResult.getResult(), IDinformation.class);
        	BeanUtils.copyProperties(iDinformation, iDocrResult.getResult());
        	if(!iDinformation.getName().equals(OcrName)) {
        		 return Result.error("姓名与身份证姓名不匹配");
        	}
        	if(!iDinformation.getCode().equals(OcrCode)) {
        		 return Result.error("身份证号与图片身份证号不匹配");
        	}
        	redisUtil().set(String.format(CODE,iDinformation.getCode()), iDinformation.getName(), 3L, TimeUnit.HOURS);
        	upload = fileUploadService.multiUploads(multipartFile, String.valueOf(1), id);
        	return Result.success(upload);
        }
        if("2".equals(iDocrResult.getCode())) {
        	upload = fileUploadService.multiUploads(multipartFile, String.valueOf(2), String.valueOf(IDUtils.genItemId(12)));
        	return Result.success(upload);
        }
        if("-1".equals(iDocrResult.getCode())) {
       	 	return Result.error("图像为空");
        }
	   	if("-2".equals(iDocrResult.getCode())) {
	   		return Result.error("图像格式错误");
	   	}
	   	if("-3".equals(iDocrResult.getCode())) {
	   		return Result.error("图像无法加载");
	   	}
	   	if("-4".equals(iDocrResult.getCode())) {
	   		return Result.error("图像无法识别");
	   	}
	   	if("-7".equals(iDocrResult.getCode())) {
	   		return Result.error("身份证图片不完整");
	   	}
	   	if("-8".equals(iDocrResult.getCode())) {
	   		return Result.error("图片请对应相应的格式");
	   	}
	   	if("-9".equals(iDocrResult.getCode())) {
	   		return Result.error("没有信息");
	   	}else {
        	return Result.error("身份证上传失败");
		}
    }

    public static String commpressPicForScale(String srcPath, String desPath,
                                              long desFileSize, double accuracy, int desMaxWidth, int desMaxHeight) {
        if (StringUtils.isEmpty(srcPath) || StringUtils.isEmpty(srcPath)) {
            return null;
        }
        if (!new File(srcPath).exists()) {
            return null;
        }
        try {
            File srcFile = new File(srcPath);
            long srcFileSize = srcFile.length();
            System.out.println("源图片：" + srcPath + "，大小：" + srcFileSize / 1024
                    + "kb");
            //获取图片信息
            BufferedImage bim = ImageIO.read(srcFile);
            int srcWidth = bim.getWidth();
            int srcHeight = bim.getHeight();

            //先转换成jpg
            Thumbnails.Builder builder = Thumbnails.of(srcFile).outputFormat("jpg");

            // 指定大小（宽或高超出会才会被缩放）
            if (srcWidth > desMaxWidth || srcHeight > desMaxHeight) {
                builder.size(desMaxWidth, desMaxHeight);
            } else {
                //宽高均小，指定原大小
                builder.size(srcWidth, srcHeight);
            }

            // 写入到内存
            ByteArrayOutputStream baos = new ByteArrayOutputStream(); //字节输出流（写入到内存）
            builder.toOutputStream(baos);

            // 递归压缩，直到目标文件大小小于desFileSize
            byte[] bytes = commpressPicCycle(baos.toByteArray(), desFileSize, accuracy);

            // 输出到文件
            File desFile = new File(desPath);
            FileOutputStream fos = new FileOutputStream(desFile);
            fos.write(bytes);
            fos.close();
            System.out.println("目标图片：" + desPath + "，大小" + desFile.length() / 1024 + "kb");
            System.out.println("图片压缩完成！");
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
        return desPath;
    }

    private static byte[] commpressPicCycle(byte[] bytes, long desFileSize, double accuracy) throws IOException {
        // File srcFileJPG = new File(desPath);
        long srcFileSizeJPG = bytes.length;
        // 2、判断大小，如果小于500kb，不压缩；如果大于等于500kb，压缩
        if (srcFileSizeJPG <= desFileSize * 1024) {
            return bytes;
        }
        // 计算宽高
        BufferedImage bim = ImageIO.read(new ByteArrayInputStream(bytes));
        int srcWdith = bim.getWidth();
        int srcHeigth = bim.getHeight();
        int desWidth = new BigDecimal(srcWdith).multiply(
                new BigDecimal(accuracy)).intValue();
        int desHeight = new BigDecimal(srcHeigth).multiply(
                new BigDecimal(accuracy)).intValue();

        ByteArrayOutputStream baos = new ByteArrayOutputStream(); //字节输出流（写入到内存）
        Thumbnails.of(new ByteArrayInputStream(bytes)).size(desWidth, desHeight).outputQuality(accuracy).toOutputStream(baos);
        return commpressPicCycle(baos.toByteArray(), desFileSize, accuracy);
    }

    @GetMapping("getReal")
    @ApiOperation(value = "查询账号资料", notes = "查询账号资料")
    public Result<SysAdminDetailVo> getReal(HttpServletRequest request) {
        try {
            String token = request.getHeader("authorization");
            // step1. 解析token
            Claims claims = JwtUtils.builder().token(token).build().claims();
            // step2. 从token获取参数,获取账号类型
            String adminId = claims.get("id").toString();
            SysAdminDetailVo sysAdminDetailVo = sysAdminDetailService.selectAttaUpload(adminId);
            sysAdminDetailVo.getAttaUploadList().forEach(f -> {
                f.setUrl(projectConfiguration.getStaticResource().getStaticResourceUrl() + "/" + f.getUrl());
            });
            return Result.success(sysAdminDetailVo);
        } catch (Exception e) {
            e.printStackTrace();
            throw new BusinessException("查询账号资料失败");
        }
    }
}
